<template>
  <div class="container" ref="mainCon">
    <div class="mainCon">
      <el-row
        class="toolbar searchInputWidth"
        style="padding-bottom: 0; margin-bottom: 0"
      >
        <el-form :inline="true" :model="filterField">
          <el-col :lg="8" :xl="6">
            <el-form-item label="区域" class="row-padding-bottom">
              <el-cascader
                v-model="areaId"
                ref="refHandle"
                :options="areasOptions"
                :props="{ checkStrictly: true }"
                @change="handleChange"
                clearable
                :append-to-body="false"
              ></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :lg="8" :xl="6">
            <el-form-item label="银行" class="row-padding-bottom">
              <el-select
                v-model="filterField.bankId"
                clearable
                filterable
                placeholder="请选择"
                :popper-append-to-body="false"
              >
                <el-option
                  v-for="(item, index) of bankData"
                  :key="index"
                  :label="item.name"
                  :value="item.code"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-form-item>
            <!-- <el-button type="primary" icon="icon iconfont iconchazhao1" @click="searchList" class="commonBtn"></el-button> -->
            <el-button
              type="primary"
              icon="icon iconfont iconchazhao1"
              @click="searchList"
              class="searchBtn"
            >
              <span>搜索</span>
            </el-button>
            <exportBtn
              v-if="!isShowAdd"
              :dataLen="tableList.length"
              :filterField="filterField"
              api="api-s/report/export_JC_CS_DEPOSIT_SET_BANK"
            ></exportBtn>
          </el-form-item>
          <!-- <el-form-item>
            </el-form-item>
            <el-form-item>
              <el-button :disabled="isDisabled" class="commonBut saveBtn funComBut addFirstTab"  icon="icon iconfont icontianjia"  @click="addCashDeposit" v-show="isShowAdd">
                 <span class="opetareText">添加</span>
              </el-button>
            </el-form-item> -->
        </el-form>
      </el-row>
      <div class="spacing"></div>
      <div
        ref="tableBox"
        :class="hiddleToolBar ? 'tableBoxCur tableBox' : 'tableBoxCur'"
      >
        <div style="margin-bottom: 24px" v-if="isShowAdd">
          <exportBtn
            :dataLen="tableList.length"
            :filterField="filterField"
            api="api-s/report/export_JC_CS_DEPOSIT_SET_BANK"
          ></exportBtn>
          <el-button
            :disabled="isDisabled"
            class="commonBut saveBtn funComBut addFirstTab"
            icon="icon iconfont icontianjia"
            @click="addCashDeposit"
          >
            <span class="opetareText">添加</span>
          </el-button>
        </div>
        <el-table
          ref="tableBox1"
          :max-height="tableHeight"
          :data="tableList"
          :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
          highlight-current-row
          stripe
          v-loading="loading"
          @sort-change="sortChange"
          style="border: 1px solid #dfe6ec"
        >
          <el-table-column
            prop="areaName"
            label="开户区域"
            :formatter="formatTd"
            min-width="160"
          ></el-table-column>
          <el-table-column
            prop="bankName"
            label="保证金开户银行"
            :formatter="formatTd"
            min-width="160"
          ></el-table-column>
          <el-table-column
            prop="account"
            label="保证金账号"
            :formatter="formatTd"
            min-width="180"
          >
            <template slot-scope="scope">
              <p>{{ scope.row.account | deseHandler(4, 4, '*') || '' }}</p>
            </template>
          </el-table-column>
          <el-table-column
            prop="projectTotal"
            label="缴纳项目数"
            sortable="custom"
            :formatter="formatTd"
            min-width="140"
          ></el-table-column>
          <el-table-column
            prop="transferTotal"
            label="缴纳总额（万元）"
            sortable="custom"
            :formatter="formatTd"
            min-width="180"
          ></el-table-column>
          <el-table-column
            prop="balance"
            label="缴纳余额（万元）"
            sortable="custom"
            :formatter="formatTd"
            min-width="180"
          ></el-table-column>
          <el-table-column label="操作" align="left" width="130" fixed="right">
            <template slot-scope="scope">
              <div v-if="scope.row.projectTotal < 1">
                <el-link
                  type="primary"
                  @click="editCashDepositBank(scope.row)"
                  v-show="scope.row.projectTotal < 1 && isShowUpdate"
                  >修改</el-link
                >
                <el-link
                  type="primary"
                  @click="toDelCashDeposit(scope.row)"
                  v-show="scope.row.projectTotal < 1 && isShowDel"
                  >删除</el-link
                >
                <span v-show="!isShowDel && !isShowUpdate">--</span>
              </div>
              <div v-else>
                <span>--</span>
              </div>
            </template>
          </el-table-column>
          <!-- 表格数据为空时，页面显示 -->
          <div slot="empty" v-show="isShow">
            <emptyTable emptyText="暂无相关信息"></emptyTable>
          </div>
        </el-table>
        <!-- filterField为搜索条件 -->
        <!-- getTableList为获取子组件的数据 -->
        <Pagination
          ref="pagination"
          @getList="getTableList"
          :filterField="filterField"
          :requestUrl="requestUrl"
          @getpageNo="getpageNo"
          @getpageSize="getpageSize"
        ></Pagination>
      </div>
    </div>
    <el-dialog
      :title="addOrEdit == 0 ? '添加保证金开户银行' : '修改保证金开户银行'"
      :visible.sync="formVisible"
      :close-on-click-modal="false"
      @close="cancel('formData')"
      custom-class="brand-dialog-min-width"
      width="640px"
      :modal-append-to-body="false"
      :append-to-body="true"
    >
      <el-form
        :model="formData"
        :rules="formRules"
        ref="formData"
        style="padding-top: 8px"
      >
        <el-form-item
          label="区域："
          :label-width="formLabelCardWidth"
          prop="addAreaId"
        >
          <el-cascader
            class="mWidth"
            v-model="addAreaId"
            :options="areasOptions"
            :props="{ checkStrictly: true }"
            @change="handleAddAreaIdChange"
            clearable
            :disabled="formData.projectTotal > 0"
          ></el-cascader>
        </el-form-item>
        <el-form-item
          label="银行："
          :label-width="formLabelCardWidth"
          prop="bankId"
        >
          <el-select
            v-model="formData.bankId"
            placeholder="请选择"
            class="mWidth"
            clearable
            filterable
            :disabled="formData.projectTotal > 0"
          >
            <el-option
              v-for="(item, index) of bankData"
              :key="index"
              :label="item.name"
              :value="item.code"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="账号："
          :label-width="formLabelCardWidth"
          prop="account"
        >
          <el-input
            v-model="formData.account"
            autocomplete="off"
            placeholder="请输入"
            class="mWidth"
            @blur="formData.account = changeValue($event)"
            maxlength="64"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="cancel('formData')" class="cancel"
          >取消</el-button
        >
        <el-button
          type="primary"
          @click.native="saveBankInfo('formData')"
          class="save"
          :loading="canLogin"
          >保存</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { mapActions, mapState } from 'vuex'
//引导页插件
import Driver from 'driver.js' // import driver.js
import 'driver.js/dist/driver.min.css' // import driver.js css
import steps from '../../kits/cashDepositStep'

export default {
  data() {
    var checkArea = (rule, value, callback) => {
      var that = this
      if (that.addAreaId.length < 1) {
        return callback(new Error('请选择区域'))
      } else {
        callback()
      }
    }
    return {
      hiddleToolBar: false,
      tableHeight: null,
      isShow: false,
      titleText: '保证金设置',
      //表格数据
      tableList: [],
      requestUrl: 'api-d/account/expand/listbypage',
      time: [],
      areaId: '',
      addAreaId: '',
      //搜索条件
      filterField: {
        areaId: '',
        bankId: '',
      },
      pageSize: 20,
      pageNo: 1,
      areaList: [],
      bankData: [],
      loading: false,
      formVisible: false,
      //   弹窗数据
      formData: {
        areaId: '',
        bankId: '',
        account: '',
        id: '',
      },
      formRules: {
        bankId: [
          {
            required: true,
            message: '银行不能为空',
            trigger: 'change',
          },
        ],
        account: [
          {
            required: true,
            pattern: /^[^\u4e00-\u9fa5]{0,}$/,
            message: '请输入正确的账号',
            trigger: 'blur',
          },
        ],
        addAreaId: [
          {
            required: true,
            validator: checkArea,
            trigger: 'change',
          },
        ],
      },
      formLabelCardWidth: '125px',
      canLogin: false,
      addOrEdit: 0,
      tabPosition: 'setCashDeposit',
      isShowDel: '',
      isShowUpdate: '',
      isShowAdd: '',
      isDisabled: false,
    }
  },
  computed: { ...mapState(['areasOptions']) },
  created() {
    this.$nextTick(function () {
      this.$refs.pagination.getTableListData()
    })
    this.getAreas({ areaId: this.$store.state.areaInfoArr.areaId })
    this.getBankList()
    this.isShowAdd =
      this.$store.state.buttonLimitsArr.indexOf('depositSet:add') > -1
    this.isShowUpdate =
      this.$store.state.buttonLimitsArr.indexOf('depositSet:update') > -1
    this.isShowDel =
      this.$store.state.buttonLimitsArr.indexOf('depositSet:delete') > -1
  },
  mounted() {
    window.addEventListener('scroll', this.handleScroll, true)
    this.$nextTick(() => {
      this.driver = new Driver({
        className: '', // className to wrap driver.js popover
        animate: true, // Animate while changing highlighted element
        opacity: 0.7, // Background opacity (0 means only popovers and without overlay)
        padding: 0, // Distance of element from around the edges
        allowClose: false, // Whether clicking on overlay should close or not
        overlayClickNext: false, // Should it move to next step on overlay click
        doneBtnText: '关闭指引', // Text on the final button
        closeBtnText: '', // Text on the close button for this step
        nextBtnText: '下一步', // Next button text for this step
        prevBtnText: '上一步', // Previous button text for this step
        onHighlighted: (Element) => {
          //当element完全突出显示时调用
          this.isDisabled = true
        },
        onReset: (Element) => {
          //当要清除覆盖时调用
          this.isDisabled = false
          localStorage.setItem('isSetCashDepositBank', false)
        },
        onNext: (Element) => {
          //下一步
          //如果点击缴纳银行的添加按钮则跳转到缴纳比例页面
          if (Element.options.element === '.addFirstTab') {
            this.$emit('func', 'secondTab')
          }
        },
      })
      if (
        localStorage.getItem('isSetCashDepositBank') != 'false' &&
        this.$route.query.paramsType === 'setCashDeposit'
      ) {
        //解决禁用出现空白问题
        this.isDisabled = true
        this.$emit('func', 'firstTab')
        this.$nextTick(() => {
          this.driver.defineSteps(steps['two'])
          this.driver.start()
        })
      }
    })

    let that = this
    this.$nextTick(function () {
      let tableHeightCur = this.$refs.tableBox1.$el.clientHeight
      let tableTop = this.$refs.tableBox.getBoundingClientRect().top
      if (tableHeightCur + tableTop > window.innerHeight) {
        this.tableHeight =
          this.$refs.mainCon.getBoundingClientRect().height - 86
      } else {
        document.getElementsByClassName('tableBoxCur').length &&
          (document.getElementsByClassName('tableBoxCur')[0].style.height =
            window.innerHeight - tableTop - 40 + 'px')
      }

      window.onresize = function () {
        if (!that.$refs.tableBox1) {
          return
        }
        let tableHeightCur = that.$refs.tableBox1.$el.clientHeight
        let tableTop = that.$refs.tableBox.getBoundingClientRect().top
        if (tableHeightCur + tableTop > window.innerHeight) {
          that.tableHeight =
            that.$refs.mainCon.getBoundingClientRect().height - 86
        } else {
          document.getElementsByClassName('tableBoxCur').length &&
            (document.getElementsByClassName('tableBoxCur')[0].style.height =
              window.innerHeight - tableTop - 40 + 'px')
        }
      }
    })
  },
  activated() {
    window.addEventListener('scroll', this.handleScroll, true)
    this.$nextTick(function () {
      this.$refs.pagination.getTableListData(this.pageNo, this.pageSize)
      this.$refs.tableBox1.doLayout()
    })
  },
  deactivated() {
    let that = this
    window.removeEventListener('scroll', that.handleScroll, true)
  },
  beforeDestroy() {
    let that = this
    window.removeEventListener('scroll', that.handleScroll, true)
  },
  methods: {
    handleScroll(e) {
      this.$nextTick(function () {
        //变量scrollTop是滚动条滚动时，距离顶部的距离
        var scrollTop = e.target.scrollTop
        if (
          this.$refs.tableBox &&
          this.$refs.tableBox.getBoundingClientRect().top < 128
        ) {
          this.tableHeight = window.innerHeight - 240
          if (document.getElementsByClassName('tableBoxCur').length) {
            document.getElementsByClassName('tableBoxCur')[0].style.height =
              null
          }
          this.hiddleToolBar = true
        } else {
          this.hiddleToolBar = false
        }
      })
    },
    getpageSize(val) {
      this.pageSize = val
    },
    getpageNo(val) {
      this.pageNo = val
    },
    ...mapActions(['getAreas']),
    getTableList(data) {
      this.tableList = data
      this.loading = false
      if (this.tableList.length < 1) {
        this.isShow = true
      }
    },
    // 搜索
    searchList() {
      this.$refs.pagination.getTableListData()
    },
    handleChange(item) {
      var areaId = this.areaId[this.areaId.length - 1]

      this.filterField.areaId = areaId
    },
    getCheckedNodes(val) {},
    handleAddAreaIdChange(item) {
      var areaId = this.addAreaId[this.addAreaId.length - 1]

      this.formData.areaId = areaId
    },
    getBankList() {
      this.axios({
        method: 'post',
        data: { type: 'DEPOSIT_BANK' },
        url: 'api-bs/base/dicitem/findbytype',
      })
        .then(
          (response) => {
            if (!response.data.hasError) {
              this.bankData = response.data.result
            } else {
            }
          },
          (response) => {}
        )
        .catch((error) => {})
    },
    addCashDeposit() {
      this.addOrEdit = 0
      this.formVisible = true
      this.addAreaId = ''
      this.formData = {
        areaId: '',
        bankId: '',
        account: '',
        projectTotal: 0,
      }
      // 去除之前的验证
      this.$nextTick(() => {
        this.$refs.formData.clearValidate()
      })
    },
    editCashDepositBank(row) {
      this.addOrEdit = 1
      this.formVisible = true
      this.formData = {
        areaId: row.areaId,
        bankId: row.bankId,
        account: row.account,
        id: row.id,
        projectTotal: row.projectTotal,
      }
      this.addAreaId = row.areaId
    },
    saveBankInfo() {
      this.canLogin = true
      this.$refs.formData.validate((valid) => {
        if (valid) {
          this.formData.account = this.formData.account.replace(/\s+/g, '')
          if (this.addOrEdit == '0') {
            this.toAddBankInfo()
          } else {
            this.toUpdateBankInfo()
          }
        } else {
          this.canLogin = false
        }
      })
    },
    toAddBankInfo() {
      this.axios({
        method: 'post',
        url: 'api-d/account/expand/adddeposit',
        data: this.formData,
      })
        .then(
          (response) => {
            this.canLogin = false
            if (!response.data.hasError) {
              this.$message({
                message: '添加成功',
                type: 'success',
              })
              this.formVisible = false
              this.$refs.pagination.getTableListData(this.pageNo, this.pageSize)
            } else {
              this.$message({
                message: response.data.errorMsg,
                type: 'error',
              })
            }
          },
          (response) => {
            this.canLogin = false
          }
        )
        .catch((error) => {
          this.canLogin = false
        })
    },
    toUpdateBankInfo() {
      this.axios({
        method: 'post',
        url: 'api-d/account/expand/updateDeposit',
        data: this.formData,
      })
        .then(
          (response) => {
            this.canLogin = false
            if (!response.data.hasError) {
              this.$message({
                message: '修改成功',
                type: 'success',
              })
              this.formVisible = false
              this.$refs.pagination.getTableListData(this.pageNo, this.pageSize)
            } else {
              this.$message({
                message: response.data.errorMsg,
                type: 'error',
              })
            }
          },
          (response) => {
            this.canLogin = false
          }
        )
        .catch((error) => {
          this.canLogin = false
        })
    },
    cancel(formData) {
      this.$refs['formData'].resetFields()
      this.formVisible = false
    },
    toDelCashDeposit(row) {
      this.$confirm('确认删除缴存银行?', '提示', {
        cancelButtonClass: 'btn-custom-cancel',
        type: 'warning',
      })
        .then(() => {
          this.delCashDeposit(row)
        })
        .catch(() => {
          // this.$message.error("删除失败");
        })
    },
    delCashDeposit(row) {
      this.axios({
        method: 'post',
        url: 'api-d/account/expand/delete',
        data: {
          id: row.id,
        },
      })
        .then(
          (response) => {
            if (!response.data.hasError) {
              this.$message({
                message: '删除成功',
                type: 'success',
              })
              this.$refs.pagination.getTableListData(this.pageNo, this.pageSize)
            } else {
              this.$message({
                message: response.data.errorMsg,
                type: 'error',
              })
            }
          },
          (response) => {}
        )
        .catch((error) => {})
    },
  },
}
</script>

<style scoped lang="less">
//引导页添加禁用样式
.addFirstTab.el-button.is-disabled {
  color: #fff;
  background-color: #009588;
  border-color: #009588;
}
@import '../../../static/css/filterArea.less';
</style>
